<?php

namespace app\api\controller;

use addons\shopro\listener\Commission;
use addons\shopro\service\commission\Agent;
use addons\shopro\service\commission\Order as OrderService;
use addons\shopro\service\commission\Reward as RewardService;
use addons\shopro\service\Wallet;
use app\admin\model\shopro\commission\Agent as AgentModel;
use app\admin\model\shopro\commission\Level;
use app\admin\model\shopro\commission\Log as LogModel;
use app\admin\model\shopro\commission\Order as OrderModel;
use app\admin\model\shopro\commission\Reward as RewardModel;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\user\User;
use app\common\controller\Api;
use app\common\model\Userchildren;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 代理升级
     * @param $childrenId
     *
     */
    public function shengji($childrenId){
        $count = Level::where('level','>',1)->count();
        $userIdArr = Userchildren::where(['children_id'=>$childrenId])->where('level','<=',$count)->order('level asc')->column('member_id');
        if($userIdArr) {
            foreach ($userIdArr as $userId) {
                $parentInfo = \app\common\model\User::where(['id' => $userId])->where('user_type', '>', 0)->find();
                if ($parentInfo) {

                    $xiaCount = \app\common\model\User::where(['parent_user_id' => $userId,'level'=>$parentInfo['level']])->where('user_type', '=',
                        3)->count();
                    $userAgent = AgentModel::with(['level_info'])->find($userId);
                    if(empty($userAgent->level_info->upgrade_rules['child_user_count_1'])){
                        $child_user_count_1 = 3;
                    }else{
                       $child_user_count_1 = $userAgent->level_info->upgrade_rules['child_user_count_1'];
                    }
                    if($xiaCount >= $child_user_count_1){
                        //升级
//                        echo '------------------';
                        $levelInfo = Level::where('level', '>', $userAgent->level)->order('level asc')->find();
                        if($levelInfo){
                            $userAgent->level = $levelInfo->level;
                            $userAgent->save();
                            $parentInfo->level = $levelInfo->level;
                            $parentInfo->save();
                            LogModel::add($userId, 'agent', ['type' => 'level', 'level' =>  $levelInfo]);
                        }
                    }
                }
            }
        }
    }

    /**
     * 首页
     *
     */
    public function index()
    {
//        $order = db('shopro_trade_order')->where(['id'=>78])->find();
//        $data['order'] = $order;
//        $data['user'] = db('user')->where(['id'=>$order['user_id']])->find();
//        \think\Hook::listen('order_paid_commission_after', $data);
//        $orderInfo = db('shopro_trade_order')->where(['id'=>47])->find();
//        $userInfo = \app\common\model\User::where(['id'=>$orderInfo['user_id']])->find();
//        $data['order'] = $orderInfo;
//        $data['user']  = $userInfo;
//        $userInfo['id'] = 110;
//        $count = Level::where('level','>',1)->count();
//        $userIdArr = Userchildren::where(['children_id'=>$userInfo['id']])->where('level','<=',$count)->order('level asc')->column('member_id');
//        if($userIdArr) {
//            foreach ($userIdArr as $userId) {
//                $parentInfo = \app\common\model\User::where(['id' => $userId])->where('user_type', '>', 0)->find();
//                if ($parentInfo) {
//                    $xiaCount = \app\common\model\User::where(['parent_user_id' => $userId])->where('user_type', '=',
//                        3)->count();
//
//                    $userAgent = AgentModel::with(['level_info'])->find($userId);
//                    if ($userAgent->level == 1 && $xiaCount >= 3) {
//                        $levelInfo = Level::where('level', '>', 1)->order('level asc')->find();
//                        if ($levelInfo) {
//                            $userAgent->level = $levelInfo->level;
//                            $userAgent->save();
//                            $parentInfo->level = $levelInfo->level;
//                            $parentInfo->save();
//                            LogModel::add($userId, 'agent', ['type' => 'level', 'level' =>  $levelInfo]);
//                        }
//                    } else if($userAgent->level > 1 && $xiaCount >= $userAgent->level_info->upgrade_rules['child_user_count_1']){
//                            //升级
////                        echo '------------------';
//                            $levelInfo = Level::where('level', '>', $userAgent->level)->order('level asc')->find();
//                            if($levelInfo){
//                                $userAgent->level = $levelInfo->level;
//                                $userAgent->save();
//                                $parentInfo->level = $levelInfo->level;
//                                $parentInfo->save();
//                                LogModel::add($userId, 'agent', ['type' => 'level', 'level' =>  $levelInfo]);
//                            }
//                    }
//                }
//            }
//        }
        exit();
//        if($userInfo['parent_user_id'] > 0 &&  $userInfo['parent_user_id'] != $userInfo['ywy_user_id']){
//            //直推奖励
//            $parentUserInfo = \app\common\model\User::where(['id'=>$userInfo['parent_user_id'],'user_type'=>\app\common\model\User::USER_TYPE['vip_user']])->find();
//
//            if($parentUserInfo){
//                //直推
//                $agentInfo = AgentModel::with(['level_info'])->find($userInfo['parent_user_id']);
//                if(isset($agentInfo->level_info->commission_rules['commission_2']) && $agentInfo->level_info->commission_rules['commission_2'] > 0){
//                    $parentZhitui = $agentInfo->level_info->commission_rules['commission_2']/100;
//                    $zhituiCommission = $parentZhitui * $orderInfo['pay_fee'];
//                    Wallet::change($userInfo['parent_user_id'], 'commission', $zhituiCommission, 'parent_commission',['order_id'=>$orderInfo['id']],'直推佣金');
//                    $agentInfo->where(['user_id'=>$userInfo['parent_user_id']])->inc('child_order_money_1',$zhituiCommission)->inc('child_order_money_all',$zhituiCommission)->inc('child_order_count_1')->inc('child_order_count_all')->update();
//                }
//                if($parentUserInfo['ywy_user_id']){
//                    //业务员间推
//                    $ywyJiantui = sheep_config('shop.commission.ywy_jiantui')/100;
//                    $twotuiCommission =  $orderInfo['pay_fee']*$ywyJiantui;
//                    if($twotuiCommission > 0){
//                        $event  = 'ywy_jiantui_commission';
//                        $memo   = '业务员间推佣金';
//                        Wallet::change($parentUserInfo['ywy_user_id'], 'commission', $twotuiCommission, $event,['order_id'=>$orderInfo['id']],$memo);
//                        AgentModel::where(['user_id'=>$parentUserInfo['ywy_user_id']])->inc('child_order_money_2',$twotuiCommission)->inc('child_order_money_all',$twotuiCommission)->inc('child_order_count_2')->inc('child_order_count_all')->update();
//                    }
//                }
//                //间推
//                if($userInfo['two_id']){
//                    $twoUserInfo = \app\common\model\User::where(['id'=>$userInfo['two_id']])->find();
//                    if($twoUserInfo && $twoUserInfo['user_type'] == \app\common\model\User::USER_TYPE['ywy'] || $twoUserInfo['user_type'] == \app\common\model\User::USER_TYPE['vip_user']){
//                        $twotuiCommission = 0;
//                        $twoAgentInfo = AgentModel::with(['level_info'])->find($twoUserInfo['id']);
//                        if($twoUserInfo['user_type'] == \app\common\model\User::USER_TYPE['ywy']){
//                            $ywyJiantui = sheep_config('shop.commission.ywy_jiantui')/100;
//                            $twotuiCommission =  $orderInfo['pay_fee']*$ywyJiantui;
//                            $event  = 'ywy_jiantui_commission';
//                            $memo   = '业务员间推佣金';
//                        }else{
//                            if(isset($twoAgentInfo->level_info->commission_rules['commission_3']) && $twoAgentInfo->level_info->commission_rules['commission_3'] > 0){
//                                $twoZhitui = $twoAgentInfo->level_info->commission_rules['commission_3']/100;
//                                $twotuiCommission = $twoZhitui * $orderInfo['pay_fee'];
//                                $event  = 'jiantui_commission';
//                                $memo   = '间推佣金';
//                            }
//                        }
//                        if($twotuiCommission > 0){
//                            Wallet::change($twoUserInfo['id'], 'commission', $twotuiCommission, $event,['order_id'=>$orderInfo['id']],$memo);
//                            AgentModel::where(['user_id'=>$twoUserInfo['id']])->inc('child_order_money_2',$twotuiCommission)->inc('child_order_money_all',$twotuiCommission)->inc('child_order_count_2')->inc('child_order_count_all')->update();
//                        }
//
//                    }
//                }
//            }
//        }
//        chongzhiJicha($userInfo, $orderInfo['pay_fee'], $userInfo['level'], $userInfo['parent_user_id'],$orderInfo);
        exit();
        $this->success('请求成功');
    }

    public function chongzhiJicha($user, $release, $currMemberLevel, $parentUserId,$currReward = 0.00) {
        $childrenModel = new \app\admin\model\Children();
        $memberId = $childrenModel->where(['children_id' => $user['id']])->order('level', 'asc')->column('member_id');
        $flatLevelUsed = false; // 标记平级是否已经使用过
        $memberId = \app\common\model\User::where(['user_type'=>3,'status'=>'normal'])->whereIn('id', $memberId)->column('id');
        foreach ($memberId as $key => $v) {
            $currentAgent = AgentModel::where(['user_id' => $v])->with(['level_info'])->find();

            if ($currentAgent) {
                // 获取当前用户的等级
                $currentLevel = $currentAgent->level_info->level;

                // 处理级差奖
                if ($currentLevel > $currMemberLevel) {
                    $commission = $release * ($currentAgent->level_info->accelerate_scale / 100);
                    if ($commission > 0) {
                        $currCommissionReward = $commission - $currReward;
                        if ($currCommissionReward > 0) {
                            Wallet::change($v, 'commission', $currCommissionReward, 'jicha', '', '级差奖');
                            AgentModel::where(['user_id' => $v])
                                ->inc('child_order_money_2', $currCommissionReward)
                                ->inc('child_order_money_all', $currCommissionReward)
                                ->inc('child_order_count_2')
                                ->inc('child_order_count_all')
                                ->update();
                            $currReward += $currCommissionReward; // 更新当前奖励
                        }
                    }
                    // 更新当前下单人的等级
                    $currMemberLevel = $currentLevel;

                    // 处理平级奖
                } elseif ($currentLevel == $currMemberLevel && !$flatLevelUsed && $v != $parentUserId) {
                    // 避免下单人直推之间的平级奖
                    $commission = $release * ($currentAgent->level_info->parallel_scale / 100);
                    if ($commission > 0) {
                        Wallet::change($v, 'commission', $commission, 'pingji', '', '平级奖');
                        AgentModel::where(['user_id' => $v])
                            ->inc('child_order_money_2', $commission)
                            ->inc('child_order_money_all', $commission)
                            ->inc('child_order_count_2')
                            ->inc('child_order_count_all')
                            ->update();
                        $flatLevelUsed = true; // 标记平级奖已使用
                    }
                }
            }
        }
    }

    /**
     * 创建分销订单
     */
    public function createCommissionOrder($orderInfo)
    {

        $commissionOrder = OrderModel::where('order_id', $orderInfo['id'])->find();

        // 已添加过分销订单
        if ($commissionOrder) {
            return $commissionOrder;
        }

//        $commissionOrderParams = [
//            'self_buy' => 0,
//            'order_id' => $orderInfo['id'],
//            'order_item_id' => 0,
//            'buyer_id' => $orderInfo['user_id'],
//            'goods_id' => 0,
//            'agent_id' => $agentId,
//            'amount' => $this->amount,
//            'reward_type' => $this->config->getRewardType(),
//            'commission_rules' => $this->goods->getCommissionRules(),  // 记录当前设置的分佣规则，防止以后系统或者分销商设置有变导致更改历史规则
//            'reward_event' => $this->config->getRewardEvent(),
//            'commission_order_status' => $this->goods->commissionGoods->commission_order_status,  // 是否计入分销业绩
//            'commission_reward_status' => RewardModel::COMMISSION_REWARD_STATUS_PENDING,  // 佣金状态
//        ];
//
//        $commissionOrder = OrderModel::create($commissionOrderParams);
//
//        // 添加分销商推广订单业绩
//        $orderAgent = new Agent($commissionOrder->agent_id);
//        if ($orderAgent->isAgentAvaliable() && $commissionOrder->commission_order_status) {
//            if($this->selfBuy) {
//                // 添加自购业绩
//                $orderAgent->agent->setInc('child_order_money_0', $commissionOrder->amount);
//                $orderAgent->agent->setInc('child_order_count_0', 1);
//            }else {
//                // 添加一级业绩
//                $orderAgent->agent->setInc('child_order_money_1', $commissionOrder->amount);
//                $orderAgent->agent->setInc('child_order_count_1', 1);
//            }
//            LogModel::add($commissionOrder['agent_id'], 'order', [
//                'type' => 'paid',
//                'order' => $commissionOrder,
//                'item' => $this->item,
//                'buyer' => $this->buyer->user
//            ], $this->buyer->user);
//        }
//
//        return $commissionOrder;
    }

    public function ff(){
           var_dump(cache('ceshi'));
    }

    public function ceshi(){
        $commission = new Commission();
        $order = Order::with('items')->where('id', 3)->find();
        $user = User::get($order['user_id']);
        $data = ['order' => $order, 'user' => $user];
        $res = $commission->orderPaidAfter($data);
        var_dump($res);
    }
}
